package gatperdut.chato.core.messaging.replies;

import gatperdut.chato.core.ChatoServer;
import gatperdut.chato.core.messaging.grammar.messinfo.UpdateRoomsInfo;
import gatperdut.chato.core.messaging.packagers.RoomsPackager.RoomJSONAttr;
import gatperdut.chato.core.room.RoomController;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

public class UpdateRoomsReply extends Reply {

    public UpdateRoomsReply( UpdateRoomsInfo updateRoomsInfo, ChatoServer chatoServer ) {
        super( updateRoomsInfo, chatoServer );
    }

    @Override
    public String send() {
        JSONArray roomsData = getMessageInfo().getRoomsData();

        JSONObject roomData;
        RoomController roomController;
        for ( int i = 0; i < roomsData.size(); i++ ) {
            roomData = (JSONObject) roomsData.get( i );
            roomController = getChatoServer().getRoomHandler().getRoomCDOIDToController().get( roomData.get( RoomJSONAttr.ID.getName() ) );
            roomController.getRoom().setTitle( (String) roomData.get( RoomJSONAttr.TITLE.getName() ) );
        }

        getChatoServer().getDatasource().save();

        JSONObject toSend = new JSONObject();
        toSend.put( "status", "ok" );
        return toSend.toJSONString();
    }

    @Override
    public UpdateRoomsInfo getMessageInfo() {
        return (UpdateRoomsInfo) super.getMessageInfo();
    }

}
